package com.thfw.test.utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;

import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.thfw.test.model.Version;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;


/**
 * Created by scooper_lxx on 2016/5/19.
 */
public class ApplicationUtil {


    public static AlertDialog upDateDialog;

    /**
     * 双向验证的版本名：需要将（）换为_
     */
    public static String getVersionName(Context context) {
        String version =  getPackageInfo(context).versionName;
        return version.replace("(", "_")
                .replace(")","");
    }

    //版本号
    public static int getVersionCode(Context context) {
        return getPackageInfo(context).versionCode;
    }

    /**
     *
     * @param context
     * @param newVersion
     * @return  0为不更新，1为提示更新
     */
    @Deprecated
    public static boolean dealVersion(Context context, String newVersion){
        String oldVersion = ApplicationUtil.getVersionName(context);

        if(newVersion.compareTo(oldVersion)>0){
            return true;
        }else {
            return false;
        }
    }

    /**
     *
     * @param context
     * @param newVersion
     * @return  0为不更新，1为提示更新
     */
    public static boolean dealVersion(Context context, Version newVersion){
       int oldVersionCode =  ApplicationUtil.getVersionCode(context);
       int newVersionCode = 0;
       try {
           newVersionCode= Integer.parseInt(newVersion.getVersionCode());
            String[] oldVersionNum = ApplicationUtil.getVersionName(context).split(".");
            String[] newVersionNum = newVersion.getVersionName().split(".");
            if (newVersionCode > oldVersionCode ) {
                return true;
            } else  {
                for (int i=0; i< oldVersionNum.length; i++) {
                    if (Integer.parseInt(oldVersionNum[i]) < Integer.parseInt(newVersionNum[i])) {
                        return true;
                    }
                }
                return false;
            }
       } catch (NumberFormatException e) {
           e.printStackTrace();
           return false;
       }
    }

    /**
     * APP更新对话框
     * @param context
     * @param version
     * @param appDownloadUrl
     */
    public static void showDownloadDialog(final Activity context, Version version, final String appDownloadUrl) {
        if (upDateDialog != null) {
            upDateDialog.dismiss();
            upDateDialog = null;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("有新的软件版本,需要更新");
        //点击对话框以外的区域是否让对话框消失
        builder.setCancelable(false);
        //设置正面按钮
        builder.setPositiveButton("更新", null);
        //如果不强制更新
        if ( version.getIsUpdateForced() == 0) {
            builder.setCancelable(false);
            builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
        }
        upDateDialog = builder.create();
        upDateDialog.show();
        upDateDialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                downloadApp(context,appDownloadUrl);
            }
        });
    }

    private static void downloadApp(Activity context, String appDownloadUrl) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(appDownloadUrl));
        context.startActivity(intent);
    }

    private static PackageInfo getPackageInfo(Context context) {
        PackageInfo pi = null;

        try {
            PackageManager pm = context.getPackageManager();
            pi = pm.getPackageInfo(context.getPackageName(),
                    PackageManager.GET_CONFIGURATIONS);

            return pi;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return pi;
    }

    public static void hideInput(Activity context, View view){
        InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        im.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    public static void toggleInput(Activity context){
        InputMethodManager im = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        im.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
    }

    /**
     * 强制隐藏输入法
     * @param activity
     * @param editText
     */
    public static void hideInput(Activity activity, EditText editText){
        activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        try{
            Class<EditText> cls = EditText.class;
            Method method = cls.getMethod("setShowSoftInputOnFocus",boolean.class);
            method.setAccessible(false);
            method.invoke(editText,false);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    public static float getProcessCpuRate(){
        float totalCpuTime1 = getTotalCpuTime();
        float processCpuTime1 = getAppCpuTime();

        try {
            Thread.sleep(360);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        float totalCpuTime2 = getTotalCpuTime();
        float processCpuTime2 = getAppCpuTime();

        float cpuRate = 100 * (processCpuTime2 - processCpuTime1)
                /(totalCpuTime2 - totalCpuTime1);
        return cpuRate;
    }

    public static long getTotalCpuTime(){
        //get system total cpu use time
        String[] cpuInfos = null;
        try{
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream("/proc/stat")),1000);
            String load = reader.readLine();
            reader.close();
            cpuInfos = load.split(" ");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        long totalCpu = Long.parseLong(cpuInfos[2])
                + Long.parseLong(cpuInfos[3]) + Long.parseLong(cpuInfos[4])
                + Long.parseLong(cpuInfos[6]) + Long.parseLong(cpuInfos[5])
                + Long.parseLong(cpuInfos[7]) + Long.parseLong(cpuInfos[8]);
        return totalCpu;
    }

    public static long getAppCpuTime(){
        //get app cpu usr time
        String[] cpuInfos = null;

        try {
            int pid = android.os.Process.myPid();
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    new FileInputStream("/proc/" + pid +"/stat")),1000);


            String load = reader.readLine();
            reader.close();
            cpuInfos = load.split(" ");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        long appCpuTime = Long.parseLong(cpuInfos[13])
                + Long.parseLong(cpuInfos[14]) + Long.parseLong(cpuInfos[15])
                + Long.parseLong(cpuInfos[16]);
        return appCpuTime;

    }

}
